package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.dto.TimeAndStatusDTO;
import com.sky.dto.TimeDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Mapper;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        for (; begin.isBefore(end.plusDays(1)); begin = begin.plusDays(1)) {
            dateList.add(begin);
        }

        String join = StringUtils.join(dateList, ",");
        TurnoverReportVO result = new TurnoverReportVO();
        result.setDateList(join);

        List<Double> amountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime getBegin = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime getEnd = LocalDateTime.of(date, LocalTime.MAX);
            HashMap<Object, Object> map = new HashMap<>();
            map.put("begin", getBegin);
            map.put("end", getEnd);
            map.put("status", Orders.COMPLETED);
            Double amount = orderMapper.sumByMap(map);
            if (amount == null) {
                amount = 0D;
            }
            amountList.add(amount);
        }
        String theAmount = StringUtils.join(amountList, ",");
        result.setTurnoverList(theAmount);
        return result;
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        for (; begin.isBefore(end.plusDays(1)); begin = begin.plusDays(1)) {
            dateList.add(begin);
        }
        String join = StringUtils.join(dateList, ",");
        UserReportVO result = new UserReportVO();
        result.setDateList(join);
        List<Integer> newUserlist = new ArrayList<>();
        List<Integer> allUserlist = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime getBegin = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime getEnd = LocalDateTime.of(date, LocalTime.MAX);
            HashMap<Object, Object> map = new HashMap<>();
            map.put("end", getEnd);
            Integer allUser = userMapper.countByTime(map);
            if (allUser == null) {
                allUser = 0;
            }
            allUserlist.add(allUser);
            map.put("begin", getBegin);
            Integer newUser = userMapper.countByTime(map);
            if (newUser == null) {
                newUser = 0;
            }
            newUserlist.add(newUser);
        }
        String newUser = StringUtils.join(newUserlist, ",");
        String allUser = StringUtils.join(allUserlist, ",");
        result.setNewUserList(newUser);
        result.setTotalUserList(allUser);
        return result;
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
//        TimeDTO time = new TimeDTO(beginTime, endTime);
        TimeAndStatusDTO time = new TimeAndStatusDTO(beginTime, endTime, Orders.COMPLETED);

        //TODO_end 状态查询

        //查询时期内各个商品销量
        List<GoodsSalesDTO> goods = orderDetailMapper.getEachNumByTime(time);

        //判空逻辑
        if (goods == null || goods.isEmpty()) {
//            StringBuilder nameSb = new StringBuilder();
//            StringBuilder numSb = new StringBuilder();
//            for (int i = 0; i < 10; i++) {
//                nameSb.append("Null,");
//                numSb.append("0,");
//            }
//            nameSb.deleteCharAt(nameSb.length() - 1);
//            numSb.deleteCharAt(numSb.length() - 1);
//            return new SalesTop10ReportVO(nameSb.toString(), numSb.toString());
            return new SalesTop10ReportVO("", "");
        }

        //按销量从高到低排序
//        goods.sort((a, b) -> b.getNumber() - a.getNumber());

        //规整数据，goods数量规约到10;
//        int size = goods.size();
//        if (size > 10) {
//            for (int i = 0; i < size - 10; i++) {
//                goods.remove(goods.size() - 1);
//            }
//        } else
//        if (size < 10) {
//            for (int i = 0; i < 10 - size; i++) {
//                goods.add(new GoodsSalesDTO("Null", 0));
//            }
//        }

        //组装返回结果
        StringBuilder nameSb = new StringBuilder();
        StringBuilder numSb = new StringBuilder();
        for (GoodsSalesDTO good : goods) {
            nameSb.append(good.getName() + ",");
            numSb.append(good.getNumber() + ",");
        }
        nameSb.deleteCharAt(nameSb.length() - 1);
        numSb.deleteCharAt(numSb.length() - 1);
        return new SalesTop10ReportVO(nameSb.toString(), numSb.toString());
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //查询数据库
        LocalDate end = LocalDate.now().minusDays(1);
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        BusinessDataVO data = workspaceService.getBusinessData(beginTime, endTime);

        //写入excel
        InputStream input = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(input);
            XSSFSheet sheet = excel.getSheetAt(0);

            sheet.getRow(1).getCell(1).setCellValue("时间：" + beginTime + "至" + endTime);

            //填充概览数据
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(data.getTurnover());
            row.getCell(4).setCellValue(data.getOrderCompletionRate());
            row.getCell(6).setCellValue(data.getNewUsers());

            row = sheet.getRow(4);
            row.getCell(2).setCellValue(data.getValidOrderCount());
            row.getCell(4).setCellValue(data.getUnitPrice());

            //填充每一天明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                data = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(data.getTurnover());
                row.getCell(3).setCellValue(data.getValidOrderCount());
                row.getCell(4).setCellValue(data.getOrderCompletionRate());
                row.getCell(5).setCellValue(data.getUnitPrice());
                row.getCell(6).setCellValue(data.getNewUsers());
            }

            //下载到客户端浏览器
            ServletOutputStream output = response.getOutputStream();
            excel.write(output);
            //关闭资源
            output.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
